import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
const privateKey = "3j36zkuk1220"; //token私钥
//token加密,token失效时间7d=>7天

export function tokens(data, time = "1d") {
  try {
    return jwt.sign(data, privateKey, { expiresIn: time });
  } catch (e) {
    return null;
  }
}
//token解密
export function tokenv(token) {
  try {
    if (!token) throw { code: "-2", message: "登陆超时，请重新登录" };
    let time = (new Date().getTime() / 1000).toFixed(0) * 1;
    // console.log(jwt.verify(token, privateKey).exp, new Date(new Date().getTime()).getTime());
    if (jwt.verify(token, privateKey).exp <= time) {
      throw { code: "-2", message: "登陆超时，请重新登录" };
    }
    return jwt.verify(token, privateKey);
  } catch (error) {
    return error;
  }
}
//密码比较
export function passwordCompare(compar, correct) {
  if (typeof correct !== "string" || typeof compar !== "string") {
    return false;
  }
  return bcrypt.compareSync(compar, correct);
}
//密码加密
export function passwordEncrypt(password) {
  if (typeof password !== "string") {
    return false;
  }
  return bcrypt.hashSync(password, 10);
}
// console.log(
//   passwordCompare("123456", "$2a$10$Uc2BxVxAuCN57QoFO69rs.p0BIAnve5w0LqcbvOn4Q.6emzQCZ1eO")
// );
